package site.xuxingcan.NettyUtil.Handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import site.xuxingcan.Model.LoginModel;
import site.xuxingcan.NettyUtil.DataUtil;
import site.xuxingcan.NettyUtil.NettyUtil;

import java.util.Random;

/**
 * Created by xuxingcan on 16-7-25.
 */
public class LoginHandler extends SimpleChannelInboundHandler<LoginModel> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, LoginModel loginModel) throws Exception {
        loginModel.setLogin(true);
        loginModel.setRandomString(getRandomString(20));
        DataUtil.addNewShutDownOldIfNecessary(loginModel, channelHandlerContext);
        channelHandlerContext.writeAndFlush(NettyUtil.gson.toJson(loginModel));
    }

    /**
     * length表示生成字符串的长度
     *
     * @param length
     * @return
     */
    public static String getRandomString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
}